package com.harunasan.carrental.api.serve.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.VoidResult;
import com.harunasan.carrental.api.serve.oss.config.AliyunOssConfig;
import com.harunasan.carrental.api.serve.oss.service.FileService;
import com.harunasan.carrental.common.exception.OperationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
/**
 * @author LiangYi
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                AliyunOssConfig.ENDPOINT,
                AliyunOssConfig.KEY_ID,
                AliyunOssConfig.KEY_SECRET);

        // 判断BUCKET_NAME是否存在
        if(!ossClient.doesBucketExist(AliyunOssConfig.BUCKET_NAME)){
            ossClient.createBucket(AliyunOssConfig.BUCKET_NAME);
            ossClient.setBucketAcl(AliyunOssConfig.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        // 上传文件流。
        // 文件目录结构 "avatar/2021/02/27/uuid.jpg"
        //构建日期路径
        String timeFolder = LocalDate.now().format(DateTimeFormatter.ofPattern("/yyyy/MM/dd/"));
        //文件名生成
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String key = module + timeFolder + fileName;
        PutObjectResult result=ossClient.putObject(AliyunOssConfig.BUCKET_NAME, key, inputStream);
        log.info(key);
        // 关闭OSSClient。
        ossClient.shutdown();

        //文件的url地址
        //https:// bucketname   .  endpoint / + key
        return "https://" + AliyunOssConfig.BUCKET_NAME + "." + AliyunOssConfig.ENDPOINT + "/" + key;
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                AliyunOssConfig.ENDPOINT,
                AliyunOssConfig.KEY_ID,
                AliyunOssConfig.KEY_SECRET);

        // https://srb-file-200921.oss-cn-beijing.aliyuncs.com/
        // test/2021/02/27/f1673221-efb4-4356-98f4-9f0595caa927.jpg
        String host = "https://" + AliyunOssConfig.BUCKET_NAME + "." + AliyunOssConfig.ENDPOINT + "/";
        String objectName = url.substring(host.length());
        log.info(objectName);
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        VoidResult result=ossClient.deleteObject(AliyunOssConfig.BUCKET_NAME, objectName);
        if(!result.getResponse().isSuccessful()){
            throw new OperationException("文件删除失败！");
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
